#!/usr/bin/python2
# -*- coding:utf-8 -*-

##  GeotagEoG - Geotagging solution for Eye of Gnome
##  Copyright (C) 2009-2010   Bzoloid
##
##  This program is free software; you can redistribute it and/or
##  modify it under the terms of the GNU General Public License
##  as published by the Free Software Foundation; either version 2
##  of the License, or (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to the Free Software Foundation,
##  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

#------------------------------------------------------------------------------


"""GeotagEoG plugin for Eye of Gnome."""

__version__ = '1.1.4'
__date__    = '2010-01-30'
__author__  = 'Bzoloid <bzoloid@gmail.com>'
__licence__ = 'GNU GPL v2'

import subprocess
import pygtk
pygtk.require('2.0')
import gtk
import eog

import os.path
CWD = os.path.dirname(__file__)
GLADE_UI = os.path.join(CWD, "GeoTag", "geotag.glade")

import GeoTag.map as map
map.set_web_backend("webkit")
from GeoTag.geodata import *


#------------------------------------------------------------------------------

class GeoTag(eog.Plugin):
    
    def __init__(self):
        eog.Plugin.__init__(self)
        self.win = None
    
    def activate(self, window):
        """Active le plugin (fonction appelee par EoG)."""
        print "GeoTag: activation"
        self.clipboard = None
        # Recuperation des objets
        self.win = window
        self.sidebar = self.win.get_sidebar()
        self.thumbview = self.win.get_thumb_view()
        # Construction de l'UI
        self.filename = ""
        self.build_gui()
        self.sidebar.add_page("GeoTag", self.gui_main)
        self.win.connect('key-press-event', self.ev_keypress)
        self.gui_main.connect('unrealize', self.ev_unrealize)
        self.gui_main.show_all()
        return
    
    def deactivate(self, window):
        """Desactive le plugin (fonction appelee par EoG)."""
        print "GeoTag: deactivation"
        self.sidebar.remove_page(self.gui_main)
        return
    
    def build_gui(self):
        """Charge l'interface utilisateur."""
        self.gui = gtk.Builder()
        self.gui.add_from_file(GLADE_UI)
        self.gui.connect_signals(self)
        self.gmap = map.GeoMap()
        self.gmap.set_new_coords_callback(self.ev_new_coords)
        self.gui_main = self.gui.get_object('plugincontainer')
        self.gui_main.pack_start(self.gmap, expand=False, fill=False)
        self.gui_main.reorder_child(self.gmap, 0)
        return
    
    def ev_unrealize(self, *data):
        """Nettoie les references en quittant."""
        # http://bugzilla.gnome.org/show_bug.cgi?id=460781
        print "GeoTag: cleanup"
        self.gmap = None
        self.win = None
        return
    
    def ev_update(self, *data):
        """Met a jour l'affichage."""
        print "GeoTag: update"
        try:
            f0 = self.win.get_image().get_uri_for_display()
            f = f0[7:] if f0[:7] == "file://" else ""
            t = self.win.get_image().get_thumbnail()
            self.gui.get_object('image_thumb').set_from_pixbuf(t)
        except:
            f, t, s = "", gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG
            self.gui.get_object('image_thumb').set_from_stock(t, s)
        self.gui.get_object('label_filename').set_text(f)
        if (f == "") or not any(f.endswith(e) for e in ACCEPT_EXTS):
            self.filename = ""
            self.gmap.load_blank()
            for i,t in enumerate(('lat','lng','alt')):
                self.gui.get_object('entry_'+t).set_text("")
        else:
            sz = map.WEB_SIZE[0] + 17
            if self.sidebar.get_parent().get_position() < sz:
                self.sidebar.get_parent().set_position(sz)
            self.filename = f
            coords = read_gps_data(f)
            for i,t in enumerate(('lat','lng','alt')):
                self.gui.get_object('entry_'+t).set_text(coords[i])
            self.gmap.load_map(None if coords == ["","",""] else coords[:2])
        return
    
    def ev_new_coords(self):
        """Actualise les coordonnees GPS."""
        print "GeoTag: new coords"
        c = self.gmap.coords
        c = ["", ""] if (c == None) else c
        try:
            if [float(n) for n in c] == [0,0]:
                c = ["", ""]
        except:
            pass
        self.gui.get_object('entry_lat').set_text(c[0])
        self.gui.get_object('entry_lng').set_text(c[1])
        return
    
    def ev_copy(self, *data):
        """Copie les coordonnees en memoire."""
        print "GeoTag: copy"
        self.clipboard = [ self.gui.get_object('entry_'+t).get_text()
                            for t in ('lat','lng','alt') ]
        return
    
    def ev_paste(self, *data):
        """Colle les coordonnees memorisees."""
        print "GeoTag: paste"
        if self.clipboard != None:
            for i,t in enumerate(('lat','lng','alt')):
                self.gui.get_object('entry_'+t).set_text(self.clipboard[i])
        return
    
    def ev_save(self, *data):
        """Applique les modifications."""
        try:
            f = self.gui.get_object('label_filename').get_text()
            p = self.gui.get_object('image_thumb').get_pixbuf()
        except:
            return
        c = [self.gui.get_object('entry_'+t).get_text() for t in ('lat','lng','alt')]
        dialog = self.dialog_ask(f, p)
        rep = dialog.run()
        dialog.destroy()
        if rep != gtk.RESPONSE_APPLY:
            return
        print "GeoTag: save"
        r = write_gps_data(f, c)
        if r:
            self.notify("Donn\xc3\xa9es enregistr\xc3\xa9es", "dialog-information", "low")
        else:
            self.notify("Erreur ! Sauvegarde impossible", "dialog-warning", "critical")
        return
    
    def ev_keypress(self, w, event):
        """Recupere les evenements clavier pour court-circuiter les accels."""
        f = self.win.get_focus()
        if f in [self.gui.get_object('entry_'+t) for t in ('lat','lng','alt')]:
            self.win.propagate_key_event(event)
            return True
        else:
            return False
    
    def dialog_ask(self, file, pix):
        """Cree une boite de dialogue pour confirmer l'enregistrement."""
        dialog = gtk.Dialog("Eye of Gnome - GeoTag", self.win,
                    gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
                    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_APPLY))
        dialog.connect('delete_event', lambda w,d: dialog.destroy())
        dialog.connect('destroy', lambda w: dialog.destroy())
        dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        hb = gtk.HBox(spacing=7)
        hb.set_border_width(9)
        vb = gtk.VBox(spacing=7)
        i = gtk.image_new_from_pixbuf(pix)
        hb.pack_start(i, False, True)
        l = gtk.Label()
        l.set_markup("<big><b>Enregistrer les coordonn\xc3\xa9es ?</b></big>")
        l.set_alignment(0, 0.5)
        l.set_padding(0, 3)
        l.set_single_line_mode(True)
        vb.pack_start(l, False, True)
        f = gtk.Label()
        f.set_text(file)
        f.set_alignment(0, 0.5)
        f.set_single_line_mode(True)
        f.set_ellipsize(2)
        vb.pack_start(f, True, True)
        hb.pack_start(vb, True, True)
        dialog.get_content_area().pack_start(hb, False, False)
        hb.show_all()
        return dialog
    
    def notify(self, text, icon=None, urgency=None):
        """Affiche une bulle de notification."""
        title = "Eye of Gnome - GeoTag"
        i = ["-i", icon] if icon else []
        u = ["-u", urgency] if urgency else []
        try:
            p = subprocess.Popen(["notify-send","-t","3000"] + u + i + [title,text])
            p.wait()
        except:
            pass
        return


#------------------------------------------------------------------------------


